package com.neusoft.EYSystem.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JWTTool {
    private static final String SECRET = "zhang123";
    private static final int calendarField = Calendar.SECOND;
    private static final int calendarInterval = 60 * 20;

    public  static String createToken(String userJson){
        Date iaDate = new Date();

        Calendar nowTime = Calendar.getInstance();
        nowTime.add(calendarField, calendarInterval);
        Date expireDate = nowTime.getTime();

        Map<String, Object> map = new HashMap<>();
        map.put("typ","JWT");
        map.put("alg","HS256");

        return JWT.create()
                .withHeader(map)
                .withClaim("userJson", userJson)
                .withIssuedAt(iaDate)
                .withExpiresAt(expireDate)
                .sign(Algorithm.HMAC256(SECRET));
    }

    private static Map<String, Claim> verifyToken(String token) {
        return JWT.require(Algorithm.HMAC256(SECRET))
                .build()
                .verify(token)
                .getClaims();
    }

    public static String getUserJsonFromToken(String token) {
        Map<String, Claim> claims = verifyToken(token);
        Claim userJsonClaim = claims.get("userJson");
        if (userJsonClaim != null) {
            return userJsonClaim.asString();
        }
        return null;
    }
}
